﻿using System.Web.Mvc;
using System.Web.Security;

namespace ProjetoComperio.Framework.Web.Security
{
    public class RequiresAuthenticationAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
        {
            var controllerName = actionExecutingContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = actionExecutingContext.ActionDescriptor.ActionName;
            ComperioMemberShipProvider provider = new ComperioMemberShipProvider();

            if (actionExecutingContext.HttpContext.User.Identity == null) // || !provider.UserHasPermission(controllerName, actionName, actionExecutingContext.HttpContext.User.Identity.Name))
            {
                //use the current url to edirect
                string redirectOnSuccess = actionExecutingContext.HttpContext.Request.Url.AbsolutePath;

                //send them off to the login page
                string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
                string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
                actionExecutingContext.HttpContext.Response.Redirect(loginUrl, true);

            }
        }
    }
}
